import api from "./api"

export function port(portName, data) {
	return new Promise((resolve, reject) => {
		api[portName](data).then((res) => {
			if (res.code === 201) {
				hint('请登录');
				reject(res);
				uni.removeStorageSync('token');
				// #ifdef H5
				uni.reLaunch({
					url: '/pages/login'
				});
				//  #endif
				// #ifdef MP-WEIXIN
				uni.reLaunch({
					url: '/pages/login_wechat'
				});
				//  #endif
			} else if (res.code == 202) {
				hint(res.msg);
				uni.navigateTo({
					url: '/pages/agreement?type=close_msg&title=系统维护中..'
				})
			} else if (res.code == 203) {
				hint(res.msg);
				uni.navigateTo({
					url: '/pages/user/set/setting-detail?type=mobile&title=手机号码'
				})
			} else if (res.code == 204) {
				hint(res.msg);
				uni.hideLoading();
				uni.navigateTo({
					url: '/pages/user/set/password-set?type=pay_password&title=设置支付密码'
				})
			} else if (res.code == 205) {
				uni.showModal({
					title: '请确认',
					content: '您尚未绑定邀请人，请先绑定',
					confirmColor: '#F81A2E',
					success: async function(res) {
						if (res.confirm) {
							uni.navigateTo({
								url: '/pages/user/set/setting-detail?type=parent_code&title=设置推荐人'
							})
						}
					}
				});
			} else if (res.code == 1) {
				resolve(res);
			} else {

				setTimeout(() => {
					hint(res.msg);
					reject(res);
				}, 200)
			}
		})

	});
}

// 上传图片
export function uploadImg(filePath) {
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count: 1,
			sizeType: ['compressed'],
			sourceType: ['album', 'camera'],
			success: async function(res) {
				uni.uploadFile({
					url: api.imgUrl + '/api/uploads/image',
					filePath: res.tempFilePaths[0],
					header: {},
					name: 'file',
					success: (res) => {
						let url = JSON.parse(res.data).data.url;
						resolve(url)
					}
				});
			}
		});
	})
}
export function uploadImgs(filePath) {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: api.imgUrl + '/api/uploads/image',
			filePath,
			name: 'file',
			success: (res) => {
				let url = JSON.parse(res.data).data.url;
				resolve(url)
			}
		});
	})
}

// 上传
export function uploadDirectImage(filePath) {
	return new Promise((resolve, reject) => {
		port('getQiNiuInfo').then((qiNiuInfo) => {
			const lf = filePath.split('/');
			const newName = 'user/' + lf[lf.length - 1];
			uni.showLoading({})
			uni.uploadFile({
				url: qiNiuInfo.data.url,
				filePath,
				header: {},
				name: 'file',
				formData: {
					token: qiNiuInfo.data.token,
					key: newName
				},
				success: (res) => {
					uni.hideLoading()
					try {
						const result = JSON.parse(res.data);
						resolve(qiNiuInfo.data.domain + result.key);
					} catch (e) {
						resolve(res.data);
					}
				}
			});
		});
	})
}

// 返回
export function goBack() {
	const pages = getCurrentPages()
	if (pages.length === 1) {
		if (typeof params === 'number') {
			history.go(-params)
		} else {
			history.back()
		}
	} else {
		uni.navigateBack({
			delta: 1
		})
	}
}

// 跳转
export function goUrl(url, type = 1) {
	if (type == 1) {
		uni.navigateTo({
			url
		})
	} else {
		// #ifdef H5
		const newURL = uni.getStorageSync('token') ? url : '/pages/login';
		//  #endif
		// #ifdef MP-WEIXIN
		const newURL = uni.getStorageSync('token') ? url : '/pages/login_wechat';
		//  #endif

		uni.navigateTo({
			url: newURL
		})
	}

}

export function goIndex(url) {
	uni.reLaunch({
		url
	})
}

export function goRedirect(url) {
	uni.redirectTo({
		url
	})
}


// 消息提示
export function hint(data) {


	uni.showToast({
		title: data,
		icon: 'none'
	})
}

export function showPreviewImage(data) {


	uni.previewImage({
		urls: data
	});
}

// 加载中
export function loading(text = '加载中...') {
	uni.showLoading({
		title: text
	})
}

export function closeLoading() {
	uni.hideLoading();
}

export function isFloat(value) {
	return value.toString().includes('.');
}

export async function uploadFile({
	files,
	formData
}) {
	uni.showLoading()
	const executionQueue = []
	for (let iterator of files) {
		executionQueue.push(new Promise((resolve, reject) => {
			uni.uploadFile({
				url: api.imgUrl + '/api/gallery/upload',
				filePath: iterator,
				formData,
				success: (res) => {
					const data = JSON.parse(res.data)
					if (data.code === 1) {
						resolve(data.data.url)
					} else {
						hint(data.msg)
						reject(data)
					}
				},
				complete: () => {
					uni.hideLoading()
				}
			});
		}))
	}
	const result = await Promise.all(executionQueue)
	if (result.length <= 1) {
		return result[0]
	} else {
		return result
	}
}

export const imgUrl = api.imgUrl
export const productionUrl = api.productionUrl
export const serviceUrl = api.serviceUrl